﻿using Client.Hotfix;
using System;
using System.Collections.Generic;
using UnityEngine;

namespace Client.Base
{
    public class BaseWSClient<T> : ILogic where T : WSSession, new()
    {
        private string wss;
        private WSService<T> client;
        public int maxReconnectCount = 3;
        public int curReconectCount = 0;
        public bool IsConnected ;
        private Action<int, GameMessage> messageHandle;
        private readonly Queue<GameMessage> messagPackages = new();
        public BaseWSClient(string wss, Action<int, GameMessage> messageHandle)
        {
            this.messageHandle = messageHandle;
            this.wss = wss;
        }
        public void Awake()
        {
            client = new WSService<T>();
            client.BuildClient(wss);
        }

        public void Tick()
        {
            while (messagPackages.Count > 0)
            {
                if (messagPackages.TryDequeue(out var message))
                {
                    messageHandle?.Invoke(message.ReqId, message);
                }
            }
        }
        public void Reconnect()
        {
            client = new WSService<T>();
            client.BuildClient(wss);
            curReconectCount++;
            this.Log($"BaseWSClient is Reconnect ...{curReconectCount}");
        }

        public bool Send(byte[] buffer)
        {
            try
            {
         
                if(IsConnected)
                  client.session.Send(buffer);

                return true;
            }
            catch
            {
                this.Log("Send Message Error !!!!!");
                return false;
            }
        }

        public void Send(string message)
        {
            if (IsConnected)
            {
                bool succSend = client.session.Send(message);

                if (succSend)
                {
                    this.Log($"[ws][c] {message}");
                }
            }
       
        }

        public void OnReceiveMessage(byte[] buffer)
        {
            GameMessage message = buffer.ToMessage();
            //this.Log($"[ws][s] : {message.ToJson()}");
            messagPackages.Enqueue(message);
        }

        public void OnReceiveMessage(string message)
        {

        }
        public void Destroy()
        {
            curReconectCount = 0;
            client?.CloseClient();
        }
    }

}
